package com.yunxi.service.dubboService.impl.sto;

import com.alibaba.cloud.context.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunxi.core.base.Constant;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.dealer.pojo.PartnerVO;
import com.yunxi.dealer.service.PartnerDubboService;
import com.yunxi.model.sto.StoTransportOrder;
import com.yunxi.model.sto.StoTransportOrderDetail;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.service.localService.sto.StoReceiveRecordService;
import com.yunxi.service.localService.sto.StoTransportOrderDetailService;
import com.yunxi.service.localService.sto.StoTransportOrderService;
import com.yunxi.service.localService.sto.VehicleOfflineService;
import com.yunxi.sto.pojo.StoTransportOrderVO;
import com.yunxi.sto.service.StoTransportOrderDubboService;
import com.yunxi.sys.pojo.AreaVO;
import com.yunxi.sys.service.AreaDubboService;
import com.yunxi.tmsToBiz.pojo.TmsIntoShopVO;
import com.yunxi.tmsToBiz.pojo.TmsNewTransportOrderVO;
import com.yunxi.tmsToBiz.pojo.TmsPositionTailVO;
import com.yunxi.tmsToBiz.service.TmsPartnerReceiveService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * TMS推送渠道商车辆签收记录到PMS 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-06-10
 */

public class TmsPartnerReceiveServiceImpl implements TmsPartnerReceiveService {

    @Autowired
    @Qualifier(value = "stoReceiveRecordServiceImpl")
    StoReceiveRecordService stoReceiveRecordService;

    @Autowired
    PartnerDubboService partnerDubboService;


    @Autowired
    AreaDubboService areaDubboService;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineServiceImpl;


    @Autowired
    @Qualifier(value = "stoTransportOrderDubboServiceImpl")
    StoTransportOrderDubboService stoTransportOrderDubboService;

    @Autowired
    @Qualifier(value = "stoTransportOrderServiceImpl")
    StoTransportOrderService stoTransportOrderService;

    @Autowired
    @Qualifier(value = "stoTransportOrderDetailServiceImpl")
    StoTransportOrderDetailService stoTransportOrderDetailService;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineService;

    private static final Logger logger = LoggerFactory.getLogger(TmsPartnerReceiveServiceImpl.class);

    /**
     * 新增到店签收记录
     * @param list list
     * @return r
     */
    @Override
    public ApiResult savePartnerReceiveService(List<TmsIntoShopVO> list) throws Exception{
        if(list != null && list.size() > 0){
            for (TmsIntoShopVO vo : list){
                String vin = vo.getVin();
                String loadCode = vo.getLoadCode();
                StoTransportOrderDetail stoTransportOrderDetail = getStoTransportOrderDetail(vin, loadCode);
                if(stoTransportOrderDetail == null){
                    logger.debug("=================车辆VIN码:"+vin+"不存在运单信息!==================");
                    return ResponseUtil.fail(Constant.TMS_R_CODE_ERR,"车辆VIN码:"+vin+"不存在运单信息!");
                }
                else{
                    String arriveTime = vo.getArriveTime();
                    if(StringUtils.isNotEmpty(arriveTime)){
                        try {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date parse = simpleDateFormat.parse(arriveTime);
                            stoTransportOrderDetail.setArriveTime(parse);
                        }
                        catch (ParseException e){
                            logger.debug("==========================到店时间:"+arriveTime+"格式异常!===============================");
                            return ResponseUtil.fail(Constant.TMS_R_CODE_ERR,"到店时间:"+arriveTime+"格式异常!");
                        }
                    }
                    stoTransportOrderDetail.setSignatory(vo.getSignatory());//签收人
                    stoTransportOrderDetail.setSignatoryTel(vo.getSignatoryTEL());//签收人电话
                    //1.更新发运子单
                    stoTransportOrderDetailService.saveOrUpdate(stoTransportOrderDetail);
                    //2更新主单TMS送达时间
                    QueryWrapper<StoTransportOrder> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("TRANSPORT_ORDER_NO",stoTransportOrderDetail.getTransportOrderNo());
                    StoTransportOrder stoTransportOrder = stoTransportOrderService.getOne(queryWrapper);
                    if(stoTransportOrder != null && stoTransportOrder.getEndTransportTime() == null){
                        stoTransportOrder.setEndTransportTime(new Date());
                        stoTransportOrderService.saveOrUpdate(stoTransportOrder);
                    }
                }
            }
            return ResponseUtil.ok("success");
        }
        else{
            logger.debug("===================TMS到店信息接口为空!=======================");
            return ResponseUtil.fail(Constant.TMS_R_CODE_ERR,"TMS到店信息接口为空!");

        }
    }

    /**
     * 新增发运单
     * @param tmsNewTransportOrderVO
     */
    @Override
    public ApiResult addTransportOrder(TmsNewTransportOrderVO tmsNewTransportOrderVO) throws Exception {
        StoTransportOrderVO stoTransportOrderVO = new StoTransportOrderVO();
        stoTransportOrderVO.setTransportOrderNo(tmsNewTransportOrderVO.getLoadCode());//发运单号
        stoTransportOrderVO.setCarrierCode(tmsNewTransportOrderVO.getCarrierCode());//承运商代码
        stoTransportOrderVO.setCarrierName(tmsNewTransportOrderVO.getCarrierName());//承运商名称
        stoTransportOrderVO.setTransportLicense(tmsNewTransportOrderVO.getTransportVehiclePlate());//运输车牌号
        stoTransportOrderVO.setTransportDriverName(tmsNewTransportOrderVO.getDriverName());//运输司机姓名
        stoTransportOrderVO.setTransportDriverPhone(tmsNewTransportOrderVO.getDriverCellPhoneNumber());//司机电话
        stoTransportOrderVO.setPartnerCode(tmsNewTransportOrderVO.getDeliveryCode());//渠道商代码
        stoTransportOrderVO.setCarriageType(9);
        PartnerVO partnerVO = new PartnerVO();
        partnerVO = partnerDubboService.load(tmsNewTransportOrderVO.getDeliveryCode(),"pms");
        if(partnerVO != null){
            stoTransportOrderVO.setPartnerName(partnerVO.getPartnerName());
            AreaVO areaVO = new AreaVO();
            areaVO = areaDubboService.getById(partnerVO.getCity());
            if(areaVO != null){
                stoTransportOrderVO.setEndCityName(areaVO.getName());
            }
            stoTransportOrderVO.setEndCityCode(partnerVO.getCity());
        }
//        stoTransportOrderVO.setOrderState(1);
        stoTransportOrderVO.setCreateBy("TMS接口");
//        stoTransportOrderVO.setApproveStatus(2);//2新建 0通过 1  驳回
        stoTransportOrderVO.setShippingRoad(tmsNewTransportOrderVO.getShippingRoad());
        VehicleOffline vehicleOffline = new VehicleOffline();
        vehicleOffline = vehicleOfflineServiceImpl.getByVin(tmsNewTransportOrderVO.getVin());
        String shippingTime = tmsNewTransportOrderVO.getShippingTime();//预计发运时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if(StringUtils.isNotEmpty(shippingTime)){
                Date planShippingDate = simpleDateFormat.parse(shippingTime);
                stoTransportOrderVO.setPlanArrivedTime(planShippingDate);//预计板车到达工厂时间
            }
        }catch (ParseException e){
            logger.debug("预计发运时间:"+shippingTime+"格式错误!");
            return ResponseUtil.fail(Constant.TMS_R_CODE_ERR,"预计发运时间:"+shippingTime+"格式错误!");
        }
        //新增发运主单
        stoTransportOrderVO.setShippingRoad(tmsNewTransportOrderVO.getShippingRoad());//发运道次
        //查询该单号是否已存在记录,存在即做更新
        QueryWrapper<StoTransportOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TRANSPORT_ORDER_NO",tmsNewTransportOrderVO.getLoadCode());
        StoTransportOrder stoTransportOrder = stoTransportOrderService.getOne(queryWrapper);
        if(stoTransportOrder != null){
            stoTransportOrderVO.setTransportOrderId(stoTransportOrder.getTransportOrderId());
        }
        stoTransportOrderDubboService.saveOrUpdate(stoTransportOrderVO);
        //新增发运子单
        StoTransportOrderDetail stoTransportOrderDetail = new StoTransportOrderDetail();
        stoTransportOrderDetail.setTransportOrderNo(tmsNewTransportOrderVO.getLoadCode());
        stoTransportOrderDetail.setVin(tmsNewTransportOrderVO.getVin());
        stoTransportOrderDetail.setCarRoad(tmsNewTransportOrderVO.getCarRoad());
        try {
            if(StringUtils.isNotEmpty(shippingTime)){
                Date planShippingDate = simpleDateFormat.parse(shippingTime);
                stoTransportOrderDetail.setPlanSendTime(planShippingDate);
            }
        }catch (ParseException e){
            logger.debug("预计发运时间:"+shippingTime+"格式错误!");
            return ResponseUtil.fail(Constant.TMS_R_CODE_ERR,"预计发运时间:"+shippingTime+"格式错误!");
        }
        stoTransportOrderDetail.setCreateBy("TMS接口");
        QueryWrapper<StoTransportOrderDetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("TRANSPORT_ORDER_NO",tmsNewTransportOrderVO.getLoadCode());
        StoTransportOrderDetail transportOrderDetail = stoTransportOrderDetailService.getOne(queryWrapper1);
        if(transportOrderDetail != null){
            stoTransportOrderDetail.setTransportOrderDetailId(transportOrderDetail.getTransportOrderDetailId());
        }
        stoTransportOrderDetailService.saveOrUpdate(stoTransportOrderDetail);
        return ResponseUtil.ok("success");
    }

    /**
     * 更新车辆在途信息
     * @param tmsPositionTailVO
     * @throws Exception
     */
    @Override
    public ApiResult updateVehicleLocationInfo(TmsPositionTailVO tmsPositionTailVO) throws Exception {
        String vin = tmsPositionTailVO.getVin();//车辆VIN码
        String loadCode = tmsPositionTailVO.getLoadCode();//发运单号
        StoTransportOrderDetail stoTransportOrderDetail = getStoTransportOrderDetail(vin, loadCode);
        if(stoTransportOrderDetail == null){
            logger.debug("=======================车辆:"+vin+"不存在发运信息==================");
            return ResponseUtil.fail(Constant.TMS_R_CODE_ERR,"车辆:"+vin+"不存在发运信息");
        }
        else {
            stoTransportOrderDetail.setStatus(tmsPositionTailVO.getStatus());//车辆状态
            stoTransportOrderDetail.setLocation(tmsPositionTailVO.getLocation());//当前位置
            String locationTime = tmsPositionTailVO.getLocationTime();
            try {
                if(StringUtils.isNotEmpty(locationTime)){
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date parse = simpleDateFormat.parse(locationTime);
                    stoTransportOrderDetail.setLocationTime(parse);//位置更新时间
                }
            }
            catch (ParseException e){
                logger.debug("=====================位置更新时间:"+locationTime+"格式异常!=========================");
                return ResponseUtil.fail(Constant.TMS_R_CODE_ERR,"位置更新时间:"+locationTime+"格式异常");
            }
            stoTransportOrderDetail.setLng(tmsPositionTailVO.getLng());//经度
            stoTransportOrderDetail.setLat(tmsPositionTailVO.getLat());//纬度
            stoTransportOrderDetailService.saveOrUpdate(stoTransportOrderDetail);

            //更新车辆流转状态为发运在途
            QueryWrapper<VehicleOffline> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("VIN",vin);
            VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper);
            if(vehicleOffline != null){
                String carState = vehicleOffline.getCarState();
                if(StringUtils.isEmpty(carState) || !carState.equals(DictConstant.VEHICLE_TURN_STATE_12FYZT)){
                    vehicleOffline.setCarState(DictConstant.VEHICLE_TURN_STATE_12FYZT);
                    vehicleOfflineService.saveOrUpdate(vehicleOffline);
                }
            }
            return ResponseUtil.ok("sucess");
        }
    }

    /**
     * 更新小车道次
     * @param tmsNewTransportOrderVO
     * @throws Exception
     */
    @Override
    public ApiResult updateCarRoad(TmsNewTransportOrderVO tmsNewTransportOrderVO) throws Exception {
        try {
            QueryWrapper<StoTransportOrderDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("TRANSPORT_ORDER_NO",tmsNewTransportOrderVO.getLoadCode());
            StoTransportOrderDetail transportOrderDetail = stoTransportOrderDetailService.getOne(queryWrapper);
            if(transportOrderDetail != null){
                transportOrderDetail.setCarRoad(tmsNewTransportOrderVO.getCarRoad());
                stoTransportOrderDetailService.saveOrUpdate(transportOrderDetail);
                return ResponseUtil.ok("success");
            }
        }
        catch (Exception e){
            return ResponseUtil.fail(Constant.TMS_R_CODE_ERR,e.toString());
        }
        return ResponseUtil.ok("success");
    }

    private StoTransportOrderDetail getStoTransportOrderDetail(String vin, String loadCode) {
        QueryWrapper<StoTransportOrderDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("VIN", vin);
        queryWrapper.eq("TRANSPORT_ORDER_NO", loadCode);
        return stoTransportOrderDetailService.getOne(queryWrapper);
    }
}
